﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;



/// <summary>
/// 用于从内存中加载已有资源
/// </summary>
public static class ResourcesBuffer
{
    private static Dictionary<string,Object> bufferList = new Dictionary<string, Object>();

    public static T Load<T>(string resourcePath) where T:Object
    {
        T gotResource = null;

        if(bufferList.ContainsKey(resourcePath))
            gotResource = GetResourceFromArray<T>(resourcePath);
        else
            gotResource = CreateResourceInMemory<T>(resourcePath);
        
        return gotResource;
    }

    public static Object Load(string resourcePath)
    {
        if(bufferList.ContainsKey(resourcePath))
            return bufferList[resourcePath];
        else
        {
            var gotFromResourcesFile = Resources.Load(resourcePath);
            bufferList.Add(resourcePath,gotFromResourcesFile);

            return gotFromResourcesFile;
        }
    }



    private static T GetResourceFromArray<T>(string resourcePath) where T:Object
    {
        var rawRearouce = bufferList[resourcePath];

        if(rawRearouce.GetType()==typeof(T))
            return rawRearouce as T;
        else
        {
            Debug.LogError("Select resource is not match given type!");
            return null;
        }
    }

    private static T CreateResourceInMemory<T>(string resourcePath) where T:Object
    {
        var gotFromResourcesFile = Resources.Load<T>(resourcePath);
        bufferList.Add(resourcePath,gotFromResourcesFile);

        return gotFromResourcesFile;
    }
}
